import store from '@/store';
import { Notification, Message } from 'element-ui';
import $ from 'jquery';
const OSS = require('ali-oss');

export async function ossPutUpload({ file }) {
  // 获取临时密钥
  await store.dispatch('sts/getSTS');
  const credentials = store.getters.stsCache; // 获取临时密钥
  const client = new OSS({
    endpoint: 'oss-cn-beijing.aliyuncs.com',
    accessKeyId: credentials.AccessKeyId,
    accessKeySecret: credentials.AccessKeySecret,
    stsToken: credentials.SecurityToken,
    bucket: 'miva-unmcc',
    secure: true
  });
  let msg = `成功取消上传!`;
  const loading = Notification({
    title: '文件上传中',
    dangerouslyUseHTMLString: true,
    message: `${file.name}<p id="progress_${file.size}" /> `,
    // offset: 60,
    duration: 0,
    position: 'bottom-right',
    onClose() {
      // 暂停分片上传方法
      client.cancel();
      Message(msg);
    }
  });
  const progress_p = $(`#progress_${file.size}`);

  let result;
  if (file.size < 10485760) {
    result = await client.put(file.name, file, {
      proeress: async function(p) {
        console.log(p);
        progress_p.html(Number(parseInt(p * 10000)) / 100 + '%');
      }
    });
  } else {
    result = await client.multipartUpload(file.name, file, {
      progress: async function(p, checkpoint) {
        console.log(p, checkpoint);
        progress_p.html(Number(parseInt(p * 10000)) / 100 + '%');
      }
    });
  }
  msg = `上传成功!`;
  loading.close();
  return result;
}
